package servlets;

import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.DBHandler;
/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
    }
    
    @Override
    public void init(){
    	try {
			super.init();
		} catch (ServletException e) {
			System.err.println("Error in initializing register servlet!!!");
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("do");
		if (action.equalsIgnoreCase("register")){
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/Register.jsp");
			dispatcher.forward(request, response);
		}
		else
			doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();		
		//DatabaseInterface simulateDB = new DBHandler();			
		String username = request.getParameter("username");		
		String password = request.getParameter("password");
		String firstName = request.getParameter("fname");
		String lastName = request.getParameter("lname");
		String email = request.getParameter("email");
		String gender = request.getParameter("gender");
		if (DBHandler.getInstance().addUser(username, firstName, lastName, password, email, gender) == 0){
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/Error.jsp");
			request.setAttribute("errorMsg", "It was not possible to add user "+username+" to the list of users. Try again!");
			request.setAttribute("errorLink", "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath());
			dispatcher.forward(request, response);
		}
		else {
			session.setAttribute("username", username);
			/*session.setAttribute("newUser", new Member(username, firstName, lastName, email, gender));//TODO delete this line when the database would exist
			session.setAttribute("password", password);//TODO delete this line when the database would exist*/
			response.sendRedirect(request.getContextPath() + "/login");
		}
	}
	
	@Override
	public void destroy(){
		super.destroy();
	}

}
